//
//  CommunityMessageViewController.m
//  Fangmm
//
//  Created by ChaoZhou on 16/3/2.
//  Copyright © 2016年 com.fangmm. All rights reserved.
//

#import "CommunityMessageViewController.h"
#import "CommunityOutLineTableViewCell.h"
#import "CommunityOtherHouseTableViewCell.h"
#import "SurroundCommunityTableViewCell.h"
#import "HttpServer.h"
#import "Community.h"
#import <UIImageView+WebCache.h>
#import "NormalCommunityTableViewCell.h"
#import "House.h"
typedef NS_ENUM(BOOL,SectionButtonState)
{
    stateOpen = YES,
    stateClose = NO
};

@interface CommunityMessageViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    SectionButtonState   section_1_BtnState;
    SectionButtonState   section_2_BtnState;
    SectionButtonState   section_3_BtnState;
    SectionButtonState   section_4_BtnState;
    SectionButtonState   section_5_BtnState;
    NSMutableArray      *surroundingCommunityArray;
    Community           *community;
    NSMutableArray      *surroundingHouseArray;
}

@end

@implementation CommunityMessageViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    surroundingHouseArray = [NSMutableArray array];
    surroundingCommunityArray = [NSMutableArray array];
    surroundingHouseArray = [NSMutableArray array];
    UIImage *leftImage = [UIImage imageNamed:@"back-18-36"];
    UIBarButtonItem *leftBar = [[UIBarButtonItem alloc]initWithImage:[leftImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(goBack)];
    self.navigationItem.leftBarButtonItem = leftBar;
    UIImage *rightImage = [UIImage imageNamed:@"share-36-36"];
    UIBarButtonItem *rightBar = [[UIBarButtonItem alloc]initWithImage:[rightImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(shareMethod)];
    self.navigationItem.rightBarButtonItem = rightBar;
    self.title = @"小区信息";
    [_mainTableView registerNib:[UINib nibWithNibName:@"CommunityOutLineTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"communityOutLineTableViewCell"];
    [_mainTableView registerNib:[UINib nibWithNibName:@"CommunityOtherHouseTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"communityOtherHouseTableViewCell"];
    [_mainTableView registerNib:[UINib nibWithNibName:@"SurroundCommunityTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"surroundCommunityTableViewCell"];
    [_mainTableView registerNib:[UINib nibWithNibName:@"NormalCommunityTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"normalCommunityTableViewCell"];
#pragma mark - 请求小区详情
    [HttpServer getCommunityWithCommunityID:self.communityId withSuccessBlock:^(NSDictionary *responseData)
    {
        community = [[Community alloc]initWithDic:responseData];
    }
    withFailBlock:^(id errorMessage)
    {
        NSLog(@"%@",errorMessage);
    }];
#pragma mark - 请求小区的其它房源
    [HttpServer getHousesWithParams:@{@"communityId":self.communityId,@"app":@"user"} WithSuccessBlock:^(NSDictionary *responseData)
    {
        NSArray *responseArray = responseData[@"houses"];
        for (NSDictionary *dic in responseArray)
        {
            House *house = [[House alloc]initWithDic:dic];
            [surroundingHouseArray addObject:house];
        }
    }
    withFailBlock:^(id errorMessage)
    {
        NSLog(@"%@",errorMessage);
    }];
#pragma mark - 请求附近小区
    [HttpServer getSourroundingCommunityWithCommunityID:self.communityId withSuccessBlock:^(NSDictionary *responseData)
    {
        NSArray *responseArray = responseData[@"communities"];
        for (NSDictionary *dic in responseArray)
        {
            Community *communityItem = [[Community alloc]initWithDic:dic];
            [surroundingCommunityArray addObject:communityItem];
        }
    }
    withFailBlock:^(id errorMessage)
    {
        NSLog(@"%@",errorMessage);
    }];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 6;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section)
    {
        case 0:
        {
            return 1;
        }
            break;
        case 1:
        {
            return 1;
        }
            break;
        case 2:
        {
            return 1;
        }
            break;
        case 3:
        {
            return 1;
        }
            break;
        case 4:
        {
            return surroundingHouseArray.count + 1;
        }
            break;
        default:
        {
            return ceilf(surroundingCommunityArray.count/3) + 1;
        }
            break;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 5;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section)
    {
        case 0:
        {
            return 140;
        }
            break;
        case 1:
        {
            return section_1_BtnState == stateOpen ? [self rectCellHeightWith:community.trafficInfos] : 151;
        }
            break;
        case 2:
        {
            return section_2_BtnState == stateOpen ? [self rectCellHeightWith:community.lifeServices] : 151;
        }
            break;
        case 3:
        {
            return section_3_BtnState == stateOpen ? [self rectCellHeightWith:community.desc] : 151;
        }
            break;
        case 4:
        {
            if (indexPath.row == 0)
            {
                return 45;
            }
            else
            {
                return 170;
            }
        }
            break;
        default:
        {
            if (indexPath.row == 0)
            {
                return 45;
            }
            else
            {
                return 150;
            }
        }
            break;
    }
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section)
    {
        case 0:
        {
            CommunityOutLineTableViewCell *communityOutLineCell = [tableView dequeueReusableCellWithIdentifier:@"communityOutLineTableViewCell"];
            [communityOutLineCell.communityImageView sd_setImageWithURL:[NSURL URLWithString:community.cover] placeholderImage:[UIImage imageNamed:@"Non_HP"]];
            communityOutLineCell.communityName.text = community.name;
            communityOutLineCell.areaLabel.text = [NSString stringWithFormat:@"%d",community.area];
            communityOutLineCell.locationLabel.text = community.location;
            communityOutLineCell.greeningLabel.text = [NSString stringWithFormat:@"%d",community.virescence];
            communityOutLineCell.yearsLabel.text = community.decade;
            return communityOutLineCell;
           
        }
            break;
        case 1:
        {
            NormalCommunityTableViewCell *tracfficTabelViewCell = [tableView dequeueReusableCellWithIdentifier:@"normalCommunityTableViewCell"];
            tracfficTabelViewCell.titleLabel.text = @"小区附近交通信息";
            CGFloat labelHeigh = [self rectLabelHeighWithString:community.trafficInfos];
            tracfficTabelViewCell.contentLabel.text = community.trafficInfos;
            [tracfficTabelViewCell.moreButton setTag:indexPath.section];
            [tracfficTabelViewCell.moreButton addTarget:self action:@selector(moreButtonAction:) forControlEvents:UIControlEventTouchUpInside];
            if (labelHeigh <=  54)
            {
                tracfficTabelViewCell.contentLabel.frame = CGRectMake(10, 56, self.view.frame.size.width - 20, 54);
            }
            else if (labelHeigh >54 && section_1_BtnState == stateOpen)
            {
                tracfficTabelViewCell.contentLabel.frame = CGRectMake(10, 56, self.view.frame.size.width - 20, labelHeigh);
            }
            else if (labelHeigh > 54 && section_1_BtnState == stateClose)
            {
                tracfficTabelViewCell.contentLabel.frame = CGRectMake(10, 56, self.view.frame.size.width - 20, 54);
            }
            tracfficTabelViewCell.bounds = CGRectMake(0, 0, self.view.frame.size.width, labelHeigh + 97);
            return tracfficTabelViewCell;
        }
            break;
        case 2:
        {
            NormalCommunityTableViewCell *lifeTabelViewCell = [tableView dequeueReusableCellWithIdentifier:@"normalCommunityTableViewCell"];
            lifeTabelViewCell.titleLabel.text = @"小区附近生活信息";
            CGFloat labelHeight =[self rectLabelHeighWithString:community.lifeServices];
            lifeTabelViewCell.contentLabel.text = community.lifeServices;
            [lifeTabelViewCell.moreButton setTag:indexPath.section];
            [lifeTabelViewCell.moreButton addTarget:self action:@selector(moreButtonAction:) forControlEvents:UIControlEventTouchUpInside];
            if (labelHeight <=  54)
            {
                lifeTabelViewCell.contentLabel.frame = CGRectMake(10, 56, self.view.frame.size.width - 20, 54);            }
            else if (labelHeight >54 && section_1_BtnState == stateOpen)
            {
                lifeTabelViewCell.contentLabel.frame = CGRectMake(10, 56, self.view.frame.size.width - 20, labelHeight);
            }
            else if (labelHeight > 54 && section_1_BtnState == stateClose)
            {
                lifeTabelViewCell.contentLabel.frame = CGRectMake(10, 56, self.view.frame.size.width - 20, 54);

            }
            lifeTabelViewCell.bounds = CGRectMake(0, 0, self.view.frame.size.width, labelHeight + 97);
            return lifeTabelViewCell;
        }
            break;
        case 3:
        {
            NormalCommunityTableViewCell *descTabelViewCell = [tableView dequeueReusableCellWithIdentifier:@"normalCommunityTableViewCell"];
            descTabelViewCell.titleLabel.text = @"小区简介";
            CGFloat labelHeight = [self rectLabelHeighWithString:community.desc];
            descTabelViewCell.contentLabel.text = community.desc;
            [descTabelViewCell.moreButton setTag:indexPath.section];
            [descTabelViewCell.moreButton addTarget:self action:@selector(moreButtonAction:) forControlEvents:UIControlEventTouchUpInside];
            if (labelHeight <=  54)
            {
                descTabelViewCell.contentLabel.frame = CGRectMake(10, 56, self.view.frame.size.width - 20, 54);
            }
            else if (labelHeight >54 && section_1_BtnState == stateOpen)
            {
                descTabelViewCell.contentLabel.frame = CGRectMake(10, 56, self.view.frame.size.width - 20, labelHeight);
            }
            else if (labelHeight > 54 && section_1_BtnState == stateClose)
            {
                descTabelViewCell.contentLabel.frame = CGRectMake(10, 56, self.view.frame.size.width - 20, 54);
            }
            descTabelViewCell.bounds = CGRectMake(0, 0, self.view.frame.size.width, labelHeight + 97);
            return descTabelViewCell;
            
        }
            break;
        case 4:
        {
//            if (surroundingHouseArray.count > 0)
//            {
//                if (indexPath.row == 0)
//                {
//                    UITableViewCell *otherHouseCell = [tableView dequeueReusableCellWithIdentifier:@"otherHouseCell"];
//                    otherHouseCell.selectionStyle = UITableViewCellSelectionStyleNone;
//                    if (!otherHouseCell)
//                    {
//                        UITableViewCell *otherHouseCell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"otherHousCell"];
//                        otherHouseCell.selectionStyle = UITableViewCellSelectionStyleNone;
//                        UILabel *titlelabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 15, 200, 20)];
//                        titlelabel.text = @"本小区的其它房源";
//                        titlelabel.font = [UIFont systemFontOfSize:15];
//                        [otherHouseCell addSubview:titlelabel];
//                    }
//                    return otherHouseCell;
//                }
//                else
//                {
//                    [self rectOtherHouseTableViewCellWithTableView:_mainTableView WithIndexPath:indexPath];
//                }
//            }
//            else
//            {
//                return nil;
//            }
            UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
            return cell;
        }
            break;
        default:
        {
            if (surroundingCommunityArray.count > 0)
            {
                switch (indexPath.row)
                {
                    case 0:
                    {
                        UITableViewCell *surroundingCommunityCell = [tableView dequeueReusableCellWithIdentifier:@"surroundingCommunityCell"];
                        if (!surroundingCommunityCell)
                        {
                            surroundingCommunityCell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"surroundCommunity"];
                            UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 15, 200, 20)];
                            titleLabel.text = @"附近小区";
                            titleLabel.font = [UIFont systemFontOfSize:15];
                            [surroundingCommunityCell addSubview:titleLabel];
                            UILabel *separateLine = [[UILabel alloc]initWithFrame:CGRectMake(10, 45, self.view.frame.size.width - 20, 1)];
                            [separateLine setBackgroundColor:[UIColor colorWithRed:204 green:204 blue:204 alpha:1]];
                            [surroundingCommunityCell addSubview:separateLine];
                        }
                        return surroundingCommunityCell;
                    }
                        break;
                    default:
                    {
                        [self addImageAndLabelForCellWithIndexPath:indexPath withTableView:_mainTableView];
                    }
                        break;
                }
            }
            else
            {
                return nil;
            }
//            UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
//            return cell;
        }
            break;
    }
    return nil;
}
-(void)goBack
{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)sectionMoreButtonClick:(UIButton*)sender
{
    
}

#pragma mark - 分享
-(void)shareMethod
{
    NSLog(@"分享方法");
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - 绘制其它房源
-(CommunityOtherHouseTableViewCell *)rectOtherHouseTableViewCellWithTableView:(UITableView *)tableView WithIndexPath:(NSIndexPath*)indepath
{
    House *houseItem = surroundingHouseArray[indepath.row - 1];
    CommunityOtherHouseTableViewCell *otherHouseCell = [tableView dequeueReusableCellWithIdentifier:@"communityOtherHouseTableViewCell"];
    //调整button的显示状态
    if (section_4_BtnState == stateClose)
    {
        otherHouseCell.moreButton.hidden = NO;
    }
    else
    {
        if (indepath.row == surroundingCommunityArray.count)
        {
            otherHouseCell.moreButton.hidden = NO;
        }
        else
        {
            otherHouseCell.moreButton.hidden = YES;
        }
    }
    [otherHouseCell.moreButton addTarget:self action:@selector(moreButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [otherHouseCell.houseImage sd_setImageWithURL:[NSURL URLWithString:houseItem.cover] placeholderImage:[UIImage imageNamed:@"block"]];
    otherHouseCell.houseName.text = houseItem.community;
    otherHouseCell.housePrice.text = [NSString stringWithFormat:@"%d",houseItem.singleRentUpper];
    NSString *descStr = [NSString stringWithFormat:@"%@|%@|%d",houseItem.community,[NSString stringWithFormat:@"%d室%d厅%d卫",houseItem.roomNum,houseItem.hallNum,houseItem.toiletNum],houseItem.area];
    otherHouseCell.houseDesc.text = descStr;
    houseItem.check == YES ? (otherHouseCell.checkImage.hidden = NO):(otherHouseCell.checkImage.hidden = NO);
    otherHouseCell.leaderLabel.text = houseItem.seeMode;
    //buttonmore
    [otherHouseCell.moreButton setTag:indepath.section];
    [otherHouseCell.moreButton addTarget:self action:@selector(moreButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    return otherHouseCell;
}
#pragma mark - 绘制附近小区
-(SurroundCommunityTableViewCell *)addImageAndLabelForCellWithIndexPath:(NSIndexPath*)indexpath withTableView:(UITableView*)tableView
{
    SurroundCommunityTableViewCell *surroundCommunityCell = [tableView dequeueReusableCellWithIdentifier:@"surroundCommunityTableViewCell"];
    //调整button的显示状态
    if (section_5_BtnState == stateClose)
    {
        surroundCommunityCell.moreButton.hidden = NO;
    }
    else
    {
        if (indexpath.row == ceilf(surroundingCommunityArray.count/3))
        {
            surroundCommunityCell.moreButton.hidden = NO;
        }
        else
        {
            surroundCommunityCell.moreButton.hidden = YES;
        }
    }
    //
    [surroundCommunityCell.moreButton addTarget:self action:@selector(moreButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [surroundCommunityCell.moreButton setTag:indexpath.section];
    //
    if (surroundingCommunityArray.count >= (indexpath.row - 1) * 3 +1)
    {
        surroundCommunityCell.communityImage_1 = surroundingCommunityArray[(indexpath.row - 1) * 3 ];
    }
    else if (surroundingCommunityArray.count >= (indexpath.row - 1) * 3 +2)
    {
        surroundCommunityCell.communityImage_2 = surroundingCommunityArray[(indexpath.row - 1) * 3 + 1];
    }
    else if (surroundingCommunityArray.count >= (indexpath.row) * 3)
    {
        surroundCommunityCell.communityImage_3 = surroundingCommunityArray[(indexpath.row - 1) * 3 + 2];
    }
    return surroundCommunityCell;
}
#pragma mark - moreButtonAction
-(void)moreButtonAction:(UIButton *)sender
{
//    switch (sender.tag)
//    {
//        case 1:
//        {
//            section_1_BtnState = !section_1_BtnState;
////            [_mainTableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationAutomatic];
//            [_mainTableView reloadData];
//        }
//            break;
//        case 2:
//        {
//            section_2_BtnState = !section_2_BtnState;
////            [_mainTableView reloadSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:UITableViewRowAnimationAutomatic];
//            [_mainTableView reloadData];
//        }
//            break;
//        case 3:
//        {
//            section_3_BtnState = !section_3_BtnState;
////            [_mainTableView reloadSections:[NSIndexSet indexSetWithIndex:3] withRowAnimation:UITableViewRowAnimationAutomatic];
//            [_mainTableView reloadData];
//        }
//            break;
//        case 4:
//        {
//            section_4_BtnState = !section_4_BtnState;
////            [_mainTableView reloadSections:[NSIndexSet indexSetWithIndex:4] withRowAnimation:UITableViewRowAnimationAutomatic];
//            [_mainTableView reloadData];
//        }
//            break;
//        default:
//        {
//            section_5_BtnState = !section_5_BtnState;
////            [_mainTableView reloadSections:[NSIndexSet indexSetWithIndex:4] withRowAnimation:UITableViewRowAnimationAutomatic];
//            [_mainTableView reloadData];
//        }
//            break;
//    }
}
-(CGFloat)rectLabelHeighWithString:(NSString *)str
{
    CGFloat labelHeight = [community.trafficInfos boundingRectWithSize:CGSizeMake(self.view.frame.size.width - 40, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:12],NSFontAttributeName, nil] context:nil].size.height;
    return labelHeight;
}
-(CGFloat)rectCellHeightWith:(NSString *)str
{
    return ([self rectLabelHeighWithString:str] + 97) < 151 ? 151 : ([self rectLabelHeighWithString:str] + 97);
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
